package com.lag.spring;

import org.springframework.aop.framework.AopContext;

import java.beans.Introspector;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class SpringApplicationContext {
    private Class appconfig;
    /**
     * 单例池
     */
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    private ArrayList<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public SpringApplicationContext(Class appconfig) {
        this.appconfig = appconfig;
        // 解析配置类
        if (appconfig.isAnnotationPresent(ComponentScan.class)){
        // ComponentScan注解 --> 扫描路径  --> 扫描
        ComponentScan componentScanAnnotation = (ComponentScan) appconfig.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScanAnnotation.value();
        // 扫描componet注解类
        // 1.根据类加载器拿到path路径下的类路径
        System.out.println("================开始扫描================");
        ClassLoader classLoader = SpringApplicationContext.class.getClassLoader();
        path = path.replace(".", "/");
        URL resource = classLoader.getResource(path);
        File file = new File(resource.getFile());
        // 判断是否为目录
        if (file.isDirectory()) {
            File[] files = file.listFiles();

            for (File f : files) {
                String fileName = f.getAbsolutePath();
                // 判断文件后缀是否为.class
                if (fileName.endsWith(".class")) {
                    String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                    className = className.replace("/", ".");

                    System.out.println(className);

                    try {
                        Class<?> aClazz = classLoader.loadClass(className);
                        // 判断是否存在component注解
                        if (aClazz.isAnnotationPresent(Component.class)) {
                            if (BeanPostProcessor.class.isAssignableFrom(aClazz)) {
                                BeanPostProcessor instance = (BeanPostProcessor) aClazz.newInstance();
                                beanPostProcessorList.add(instance);
                            }
                            Component compoent = aClazz.getAnnotation(Component.class);
                            String beanName = compoent.value();
                            if (compoent.value().equals("")){
                                beanName =  Introspector.decapitalize(aClazz.getSimpleName());
                            }
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setType(aClazz);
                            // 解析类
                            // 判断是单例bean还是原型bean
                            if (aClazz.isAnnotationPresent(Scope.class)){
                                //创建原型bean
                                Scope annotation = aClazz.getAnnotation(Scope.class);
                                beanDefinition.setScope(annotation.value());
                            }else {
                                //创建单例
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionMap.put(beanName,beanDefinition);
                        }

                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
        System.out.println(file);
        }
        System.out.println("================创建单例bean================");
        // 2.创建单例bean
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
                System.out.println("================创建["+beanName+"]单例bean================");
            }

        }

    }

    private Object createBean(String beanName, BeanDefinition beanDefinition){
        Class aClass = beanDefinition.getType();
        //TODO 如果类中有参构造方法将有问题
        // 反射 通过无参构造方法实例化
        Object o = null;
        try {
            o = aClass.getConstructor().newInstance();
            // 依赖注入
            for (Field field : aClass.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)){
                    // 修改访问权限
                    field.setAccessible(true);
                    // TODO 当前对象被代理了
                    field.set(o, getBean(field.getName()));
                }
            }
            // Aware
            if (o instanceof BeanNameAware) {
                ((BeanNameAware) o).setBeanName(beanName);
            }
            // 初始化前
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                o = beanPostProcessor.postProcessBeforeInitialization(beanName, o);
            }
            // 初始化
            if (o instanceof InitializingBean) {
                ((InitializingBean) o).afterPropertiesSet();
            }
            // 初始化后
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                o = beanPostProcessor.postProcessAfterInitialization(beanName, o);
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return o;
    }

    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null){
            throw new RuntimeException("未找到["+ beanName + "]名称的bean");
        }
        // 判断是单例还是多例
        if (beanDefinition.getScope().equals("singleton")) {
            Object bean = singletonObjects.get(beanName);
            if (bean == null){
                bean = createBean(beanName, beanDefinition);
                // 放入单例池中
                singletonObjects.put(beanName, bean);
            }
            return bean;
        }
        return createBean(beanName, beanDefinition);
    }
}
